﻿using System;

using zijian666.Converts.Abstractions;
using zijian666.Converts.Convertor.Base;
using zijian666.Converts.Core;
using zijian666.Converts.Extensions;

namespace zijian666.Converts.Convertor;

/// <summary>
/// <seealso cref="Uri"/> 转换器
/// </summary>
public class UriConvertor : AllowNullConvertor<Uri>, IFrom<string, Uri>
{
    /// <inheritdoc />
    public ConvertResult<Uri> From(IConvertContext context, string input)
    {
        if (input is null)
        {
            return default;
        }
        // 删除前空白字符
        input = input.TrimStart();
        if (Uri.TryCreate(input, UriKind.Absolute, out var result))
        {
            return new(result);
        }
        if (Uri.TryCreate("http://" + input, UriKind.Absolute, out result))
        {
            return new(result);
        }
        return context.ConvertFail(this, input);
    }
}
